import React, { useEffect, useState } from 'react';
import { View, Text, Image, StyleSheet, FlatList, TouchableOpacity, Alert, ImageBackground } from 'react-native';

import { useSelector } from 'react-redux';
import { get } from '../http/http';
import { useNavigation } from '@react-navigation/native';
import ImageConstants from '../resources/ImageConstants';
import { Select } from 'teaset';
import SegmentedControl from '@react-native-segmented-control/segmented-control';
import Row from '../components/Row';

const MainScreen = () => {
  // 如何页面加载的时候，store里面的user字段为空，那么就跳转LoginScreen
  // 否则就不跳转

  const [indexData, setIndexData] = useState(null);
  const [colleges, setColleges] = useState([]);
  const [status, setStatus] = useState('loadmore');
  const [list, setList] = useState([]);
  const [merchantId, setMerchantId] = useState('');
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const navigation = useNavigation();
  const [buildings, setBuildings] = useState([]);
  const [buildIndex, setBuildingsIndex] = useState(0);

  const user = useSelector((state: any) => state.root.user);



  useEffect(() => {
    const loadColleges = async () => {

    };
    loadColleges();
  }, []);
  const all = [{
    text: '全部',
    value: '',
  }];
  useEffect(() => {
    const loadData = async () => {
      try {
        const r = await get('base/merchant/api/findMerchantByChannelApi', { channelId: user.channelId });
        const colleges = all.concat(r.data.map((v, index) => ({
          text: v.merchantName,
          value: v.merchantId,
        })));
        setColleges(colleges);
        if (r.data.length > 0) {
          setMerchantId(r.data[0].merchantId);
        }
        else {
          setMerchantId('');
        }
        const response = await get('security/securityStatistical/api/getAppMonitoringHallIndexData');
        const data = response.data;
        setIndexData(data);
        if (user.channelId === 'ddspldgdz') {
          // 东大四牌楼
          const response2 = await get('security/securityStatistical/api/getClassroomEquipmentCache', {
            page, limit: 10, merState: 1, roomState: 1, merchantId: r.data.length > 0 ? r.data[0].merchantId : '',
          });
          console.log(JSON.stringify(response2.data));
          if (response2.data.length === 0 || response2.data[0]?.subMap?.length === 0) {
            setStatus('nomore');
            setBuildings([]);
            setList([]);
          }
          setBuildings(response2.data[0].subMap);
          setList(response2.data[0].subMap[0].roomList);
          setStatus('nomore');
        }
        else {
          const response2 = await get('security/securityStatistical/api/getAppMonitoringHallClassroomData', {
            page, limit: 10, merchantId,
          });
          setList(prevList => [...prevList, ...response2.data.data]);
          setPages(response2.data.pages);
          setStatus(page >= response2.data.pages ? 'nomore' : 'loading');
        }
      } catch (error) {
        Alert.alert('Error', error.message);
      }
    };
    if (user) {

      loadData();
    }
  }, [user, page, merchantId]);

  useEffect(() => {
    if (!user) {
      navigation.navigate('LoginScreen');
    }
    else {
      // 加载数据
    }
  }, []);


  const renderItem = ({ item }) => {
    if (user.channelId === 'ddspldgdz') {
      return (
        <TouchableOpacity onPress={() => navigation.navigate('ClassroomScreen', { classroomId: item.laboratoryId, classroomName: item.laboratoryName })} style={styles.item}>
          <Row style={{ alignSelf: 'stretch', justifyContent: 'space-between' }}>
            <Text style={{ color: '#333', fontWeight: 'bold' }}>{item.laboratoryName}</Text>
            <Text style={styles.itemLocation}>在线操作</Text>
          </Row>
        </TouchableOpacity>);
    }
    return (
      <TouchableOpacity onPress={() => navigation.navigate('ClassroomScreen', { classroomId: item.classroomId, classroomName: item.classroomName })} style={styles.item}>
        <View style={styles.itemHeader}>
          <Text style={styles.itemTitle}>{item.classroomName}</Text>
          <Text style={styles.itemLocation}>{item.classroomLocation}</Text>
        </View>
        <Text style={styles.itemLead}>负责人：{item.leadName} {item.contactPhone}</Text>
      </TouchableOpacity>
    );
  };
  console.log('楼层：', buildings.map(v => v.buildingName));
  console.log('buildIndex:', buildIndex);
  return (
    <ImageBackground style={styles.container} source={ImageConstants.INDEX_BCG}>
      <View style={styles.header}>
        <Image source={ImageConstants.INDEX_CLOUD} style={styles.image} />
        <Text style={styles.title}>国实实训管理系统</Text>
        <Text style={styles.subtitle}>管理端</Text>
      </View>
      <View style={styles.content}>
        <View style={styles.collegeInfo}>
          <Text style={styles.collegeLabel}>学院信息:</Text>
          {/* 这里需要一个选择器组件来替代 uni-data-select */}
          <Select
            onSelected={(item: any, index: number) => {
              setPage(1);
              setList([]);
              setStatus('loading');
              setMerchantId(colleges[index].value);
            }}
            value={colleges.find(v => v.value === merchantId)?.text}
            // pickerType={'popover'}
            getItemValue={(item: any, index: number) => item}
            items={colleges.map(v => v.text)}
            style={{ flex: 1 }}
          />
        </View>
        {user && user.channelId === 'ddspldgdz' && buildings && buildings.length > 0 ? <SegmentedControl
          style={{ margin: 10 }}
          values={buildings.map(v => v.buildingName)}
          selectedIndex={buildIndex}
          onChange={(event) => {
            setBuildingsIndex(event.nativeEvent.selectedSegmentIndex);
            setList(buildings[event.nativeEvent.selectedSegmentIndex].roomList);
          }}
        /> : null}
        {list.length > 0 ? (
          <View style={{ flex: 1 }}>
            <FlatList
              data={list}
              keyExtractor={(item, index) => index.toString()}
              renderItem={renderItem}
              onEndReached={() => {
                if (page < pages) {
                  setPage(page + 1);
                }
              }}
              onEndReachedThreshold={0.5}
              ListFooterComponent={() => (
                <Text style={styles.status}>{status === 'loading' ? '加载中...' : '没有更多数据了'}</Text>
              )}
            /></View>
        ) : (
          <Text style={styles.empty}>暂无数据</Text>
        )}
      </View>
    </ImageBackground>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F7F8F8',
  },
  header: {
    width: '100%',
    height: '40%',
    position: 'relative',
  },
  image: {
    width: '57%',
    position: 'absolute',
    right: 0,
    top: 50,
  },
  title: {
    fontSize: 24,
    color: 'white',
    marginLeft: 30,
    marginTop: 70,
  },
  subtitle: {
    fontSize: 30,
    color: 'white',
    marginLeft: 30,
    marginTop: 0,
  },
  content: {
    backgroundColor: '#F7F8F8',
    width: '100%',
    marginTop: 15,
    flex: 1,
    paddingTop: 10,
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    // paddingHorizontal: 12,
  },
  collegeInfo: {
    margin: 10,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#EFEFEF',
    height: 40,
    borderRadius: 20,
    paddingHorizontal: 10,
  },
  collegeLabel: {
    backgroundColor: '#4EB894',
    height: 40,
    lineHeight: 40,
    borderRadius: 20,
    paddingHorizontal: 10,
    color: 'white',
  },
  item: {
    backgroundColor: 'white',
    borderRadius: 10,
    marginVertical: 15,
    padding: 15,
    width: '90%',
    alignSelf: 'center',
  },
  itemHeader: {
    borderBottomWidth: 1,
    borderBottomColor: '#EFEFEF',
    paddingBottom: 10,
    marginBottom: 10,
  },
  itemTitle: {
    color: '#4EB894',
    fontWeight: 'bold',
  },
  itemLocation: {
    color: '#4EB894',
    fontSize: 14,
  },
  itemLead: {
    color: '#4EB894',
    fontSize: 14,
  },
  status: {
    textAlign: 'center',
    color: '#4EB894',
    marginVertical: 10,
  },
  empty: {
    textAlign: 'center',
    color: '#4EB894',
    marginVertical: 20,
  },
});
export default MainScreen;

